package serverMgr

/* Login上的Gateway的负载器 */
type ServerMapByGway struct {
	ServerMapByRand
	//服务器信息
	Allli []IServerInfo
}

func NewServerMapByGway() (result *ServerMapByGway) {
	result = new(ServerMapByGway)
	result.Srvli = make(map[uint64]map[uint64]IServerInfo)
	result.Allli = make([]IServerInfo, 0, 100)
	return
}

// 加入服务器信息
func (this *ServerMapByGway) Put(sinfo IServerInfo) {
	this.Lock.Lock()
	defer this.Lock.Unlock()
	key := uint64(sinfo.GetSrvType())<<32 + uint64(sinfo.GetGroupID())
	if li, ok := this.Srvli[key]; !ok {
		li = make(map[uint64]IServerInfo)
		this.Srvli[key] = li
		li[sinfo.GetServerID()] = sinfo
	} else {
		li[sinfo.GetServerID()] = sinfo
	}
	for i, md := range this.Allli {
		if md.GetServerID() == sinfo.GetServerID() {
			this.Allli[i] = sinfo
			return
		}
	}
	this.Allli = append(this.Allli, sinfo)

}

// 删除一个服务器信息
func (this *ServerMapByGway) Delete(path string) {
	groupid, stype, serverid := GetPathServerInfo(path)
	this.Lock.Lock()
	defer this.Lock.Unlock()
	key := uint64(stype)<<32 + uint64(groupid)
	if li, ok := this.Srvli[key]; ok {
		delete(li, serverid)
	}
	for i, md := range this.Allli {
		if md.GetServerID() == serverid {
			this.Allli = append(this.Allli[0:i], this.Allli[i+1:]...)
			return
		}
	}
}

// 更新Load值
func (this *ServerMapByGway) UpLoad(path string, val int64) IServerInfo {
	groupid, stype, sid := GetPathServerInfo(path)
	this.Lock.Lock()
	defer this.Lock.Unlock()
	key := uint64(stype)<<32 + uint64(groupid)
	if li, ok := this.Srvli[key]; ok {
		if sinfo, ok := li[sid]; ok {
			sinfo.SetLoad(val)
			return sinfo
		}
	}
	return nil
}

// 获取指定类型服务器列表
func (this *ServerMapByGway) GetListByType(styp uint32) (result []IServerInfo, err error) {
	this.Lock.RLock()
	defer this.Lock.RUnlock()
	return this.Allli, nil
}

// 删除所有服务器信息
func (this *ServerMapByGway) DeleteAll() {
	this.Lock.RLock()
	defer this.Lock.RUnlock()
	this.Srvli = make(map[uint64]map[uint64]IServerInfo)
	this.Allli = make([]IServerInfo, 0, 100)
}
